import { io, Socket } from 'socket.io-client';
import { NotificationData } from '../types/api';

class WebSocketService {
  private socket: Socket | null = null;
  private isConnected = false;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 1000;

  // 连接WebSocket
  connect(token: string): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.socket && this.isConnected) {
        resolve();
        return;
      }

      if (!token) {
        // 如果没有token，创建一个测试token
        console.log('没有提供认证token，使用测试模式');
        token = 'test-token-for-websocket';
      }

      const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3002';
      // 确保WebSocket连接到根路径，移除/api后缀
      const WS_URL = API_BASE_URL.replace('/api', '');
      console.log('尝试连接WebSocket到:', WS_URL);
      console.log('使用token:', token.substring(0, 20) + '...');
      
      this.socket = io(WS_URL, {
        transports: ['websocket', 'polling'],
        autoConnect: true,
        forceNew: true,
        // 明确指定连接到根命名空间
        path: '/socket.io/',
        // 添加超时设置
        timeout: 20000,
        // 添加重连设置
        reconnection: true,
        reconnectionAttempts: 5,
        reconnectionDelay: 1000,
      });

      // 连接成功
      this.socket.on('connect', () => {
        console.log('WebSocket连接成功, Socket ID:', this.socket?.id);
        this.isConnected = true;
        this.reconnectAttempts = 0;
        
        // 发送认证信息
        console.log('发送认证token...');
        this.socket?.emit('authenticate', token);
      });

      // 认证成功
      this.socket.on('authenticated', (data) => {
        console.log('WebSocket认证成功:', data);
        resolve();
      });

      // 认证失败
      this.socket.on('authentication_error', (error) => {
        console.error('WebSocket认证失败:', error);
        reject(new Error('WebSocket认证失败'));
      });

      // 连接错误
      this.socket.on('connect_error', (error) => {
        console.error('WebSocket连接错误:', error);
        console.error('错误详情:', error.message);
        this.handleReconnect();
        reject(error);
      });

      // 断开连接
      this.socket.on('disconnect', (reason) => {
        console.log('WebSocket断开连接:', reason);
        this.isConnected = false;
        
        if (reason === 'io server disconnect') {
          // 服务器主动断开，需要重新连接
          this.handleReconnect();
        }
      });

      // 新通知事件
      this.socket.on('new_notification', (notification: NotificationData) => {
        console.log('收到实时通知:', notification);
        this.handleNewNotification(notification);
      });
    });
  }

  // 断开连接
  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
      this.isConnected = false;
      console.log('WebSocket已断开');
    }
  }

  // 处理重连
  private handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
      
      console.log(`${delay}ms后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
      
      setTimeout(() => {
        if (this.socket && !this.isConnected) {
          this.socket.connect();
        }
      }, delay);
    } else {
      console.error('WebSocket重连失败，已达到最大重试次数');
    }
  }

  // 处理新通知
  private handleNewNotification(notification: NotificationData) {
    // 触发自定义事件，让DraggableIcon组件监听
    const event = new CustomEvent('new-notification', {
      detail: notification
    });
    window.dispatchEvent(event);
  }

  // 检查连接状态
  isSocketConnected(): boolean {
    return this.isConnected && this.socket?.connected === true;
  }

  // 获取socket实例
  getSocket(): Socket | null {
    return this.socket;
  }
}

// 创建单例实例
const webSocketService = new WebSocketService();

export default webSocketService;
